/**
 * Copyright (c) 2024 - CARThunder
 * All Rights Reserved by Chengdu CARThunder Intelligent Technology Co., LTD and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with CARThunder in writing by applicable law.
 * <p>
 * <p>
 * file description.
 *
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-07-30              junjieluo         Create it.
 */

/**
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 *
 *      Edit History
 *      ----------------------------------------------------------------------------
 *      DATE                     NAME               DESCRIPTION
 *      2024-07-30              junjieluo         Create it.
 *
 */

package com.cart.musicdemo;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.viewpager.widget.ViewPager;

import com.cart.musicdemo.adapter.ViewPagerAdapter;
import com.cart.musicdemo.base.activity.BaseActivity;
import com.cart.musicdemo.base.service.FileSystemManager;
import com.cart.musicdemo.base.service.MusicPlayerManager;
import com.cart.musicdemo.base.service.MusicService;
import com.cart.musicdemo.base.service.ProgressBarHandler;
import com.cart.musicdemo.base.utils.StorageUtils;
import com.cart.musicdemo.fragment.AlbumFragment;
import com.cart.musicdemo.fragment.ArtistFragment;
import com.cart.musicdemo.fragment.FileFragment;
import com.cart.musicdemo.fragment.PlayListFragment;
import com.cart.musicdemo.fragment.SongFragment;
import com.cart.musicdemo.model.SongModel;
import com.cart.musicdemo.model.UpdateEventUI;
import com.cart.musicdemo.receiver.UDiskReceiver;
import com.google.android.material.tabs.TabLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Main activity.
 */
public class MainActivity extends BaseActivity {

    private SeekBar seekbar;

    private TextView tvSongName;

    private ImageButton btnLast;

    private ImageButton btnStart;

    private ImageButton btnOrder;

    private ImageButton btnNext;

    private ViewPager viewPager;

    private TabLayout tabLayout;

    private ImageView albumImage;

    private TextView musicName;

    private TextView musicSinger;

    private SongModel songModel;

    private MusicPlayerManager musicPlayerManager = MusicPlayerManager.getInstance();

    //ViewPage前后预加载数量
    private static final Integer OFF_SCREEN_PAGE_LIMIT = 4;

    private ProgressBarHandler progressBarHandler;
    //播放列表
    private List<SongModel> songsList = new ArrayList<>();
    //专辑数据源
    private Map<String, List<SongModel>> albumList = new HashMap<>();
    //歌手数据源
    private Map<String, List<SongModel>> singerList = new HashMap<>();
    //所有歌曲源
    private List<SongModel> allSongs = new ArrayList<>();
    //文件夹数据源
    private FileSystemManager.FolderNode fileTreeRootNode;
    private static final String TAG = MainActivity.class.getName();


    private MusicService.MusicBinder mService;

    private AudioManager audioManager;

    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;

    private ViewPagerAdapter adapter;

    private Intent serviceIntent;

    /**
     * USB插拔监听器.
     */
    private UDiskReceiver uDiskReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        albumImage = findViewById(R.id.iv_album);
        albumImage.setImageResource(R.mipmap.empty_pic_data);
        uDiskReceiver = new UDiskReceiver();
        uDiskReceiver.setLoadApp(this::loadApp);
        // todo : 在这里补全U盘拔出后的APP停止操作
        uDiskReceiver.setStopApp(this::clearViewAndData);

        // 开始注册
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addDataScheme("file");
        registerReceiver(uDiskReceiver, filter);
    }

    private void loadApp() {
        // 设置文件扫描路径,必须要放在最前面，不然等下实例化会失败!
        FileSystemManager.setBuildPath(StorageUtils.getUsbStoragePath(this));
        //更新无数据图
        albumImage = findViewById(R.id.iv_album);
        albumImage.setImageResource(R.mipmap.u70);
        new RxPermissions(this).request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(result -> {
            if (!result) {
                showToast(getString(R.string.usb_perrmission));
            } else {
                showInitLoadView();
            }
        });

        // 初始化 AudioManager
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // 设置音频焦点监听器
        audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                switch (focusChange) {
                    case AudioManager.AUDIOFOCUS_GAIN:
                        // 重新获得音频焦点，恢复音量
                        handleAudioFocusGain();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        // 失去音频焦点，暂停或降低音量
                        handleAudioFocusLoss();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        // 短暂失去音频焦点，可以降低音量而不是完全停止
                        handleAudioFocusDuck();
                        break;
                    default:
                        // 默认情况下，记录未处理的音频焦点变化类型
                        Log.w(TAG, "Unhandled audio focus change: " + focusChange);
                }
            }
        };

        // 请求音频焦点
        if (!requestAudioFocus()) {
            Log.e(TAG, "Failed to acquire audio focus");
        }

        serviceIntent = new Intent(this, MusicService.class);
        startService(serviceIntent);
        bindService(serviceIntent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                adapter = new ViewPagerAdapter(getSupportFragmentManager());
                mService = (MusicService.MusicBinder) iBinder;
                songsList = mService.getSonglist();
                allSongs = mService.getAllSongs();
                albumList = mService.getAlbumlist();
                singerList = mService.getSingerlist();
                fileTreeRootNode = mService.getFileTreeRootNode();
                //将Service传入Fragment当中
                //播放列表歌曲初始化
                adapter.addFragment(PlayListFragment.newInstance(songsList, mService),
                        "播放列表");
                //艺术家列表初始化
                adapter.addFragment(ArtistFragment.newInstance(singerList, mService), "艺术家");
                //专辑界面初始化
                adapter.addFragment(AlbumFragment.newInstance(albumList, mService), "专辑");
                //歌曲界面初始化
                adapter.addFragment(SongFragment.newInstance(allSongs, mService), "歌曲");
                //文件列表初始化
                adapter.addFragment(FileFragment.newInstance(fileTreeRootNode, mService),
                        "文件夹");
                viewPager.setAdapter(adapter);
                viewPager.setOffscreenPageLimit(OFF_SCREEN_PAGE_LIMIT);
                tabLayout.setupWithViewPager(viewPager);
                mService.toastPathInvalid(new MusicService.CallBackPathInvalid() {
                    @Override
                    public void pathInvalid() {
                        showToast(getString(R.string.Invalid_invalid));
                    }
                });

                mService.updateMemoryPlayUi(new MusicService.CallBackUpdateMemoryPlayUi() {
                    @Override
                    public void callBackUpdateMemoryPlayUi() {
                        updateUI();
                    }
                });
                mService.updateAlbumImage(new MusicService.CallBackUpdateAlbum() {
                    @Override
                    public void updateAlbum() {
                        songModel = mService.getSongModel();
                        albumImage.setImageBitmap(songModel.getBitmap());
                        musicName.setText(songModel.getName());
                        musicSinger.setText(songModel.getSinger());
                        progressBarHandler.updateProgress();
                    }
                });
                updateUI();

            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mService = null;
                handleServiceDisconnection();
            }
        }, BIND_AUTO_CREATE);
        initData();
        initView();
    }

    // 请求音频焦点的方法
    private boolean requestAudioFocus() {
        int result = audioManager.requestAudioFocus(
                audioFocusChangeListener,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN
        );
        return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
    }

    // 音频焦点获得后处理逻辑
    private void handleAudioFocusGain() {
        // TODO: 恢复音量或播放逻辑
        if (!musicPlayerManager.isPlaying()) {
            mService.play(mService.getPosition(), false);
        }
    }

    // 音频焦点丢失后处理逻辑
    private void handleAudioFocusLoss() {
        // TODO: 降低音量或暂停播放逻辑
        if (musicPlayerManager.isPlaying()) {
            mService.play(mService.getPosition(), false);
        }
    }

    // 短暂失去焦点时的处理逻辑
    private void handleAudioFocusDuck() {
        // TODO: 减小音量逻辑
        if (musicPlayerManager.isPlaying()) {
            mService.play(mService.getPosition(), false);
        }
    }

    private void handleServiceDisconnection() {
        //mAdapter.clear();
        showNoDataView();
    }

    public void initView() {
        seekbar = (SeekBar) findViewById(R.id.seekbar);
        tvSongName = (TextView) findViewById(R.id.tvSongName);
        btnLast = (ImageButton) findViewById(R.id.btnLast);
        btnStart = (ImageButton) findViewById(R.id.btnStar);
        btnOrder = (ImageButton) findViewById(R.id.btnOrder);
        btnNext = (ImageButton) findViewById(R.id.btnNext);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        musicName = (TextView) findViewById(R.id.tv_musicName);
        musicSinger = (TextView) findViewById(R.id.tv_musicSinger);
        albumImage = (ImageView) findViewById(R.id.iv_album);

        // Init 播放 Helper 和 ProgressBarHandler
        progressBarHandler = new ProgressBarHandler(this, seekbar);
        // 初始化进度条通信
        musicPlayerManager.init(progressBarHandler, tvSongName);
        musicPlayerManager.setOnCompletionListener(mediaPlayer -> {
            //下一曲
            mService.completeNextMusic();
            updateStartButtonStatus();
        });

        initListener();

    }

    private void updateUI() {
        if (songModel != null) {
            songModel = mService.getUpdateSongModel();
            albumImage.setImageBitmap(songModel.getBitmap());
            musicName.setText(songModel.getName());
            musicSinger.setText(songModel.getSinger());
            progressBarHandler.updateProgress();
        }
    }

    public void clearViewAndData(){
        Toast.makeText(this,"开始初始化",Toast.LENGTH_LONG).show();
        //停止Service
        stopService(serviceIntent);
        //移除播放列表
        adapter.removeViewAndData();
        adapter.notifyDataSetChanged();
        //移除列表音乐
        EventBus.getDefault().post(new UpdateEventUI("clearUI"));
        albumImage.setImageResource(R.mipmap.empty_pic_data);
        musicName.setText("");
        musicSinger.setText("");
        //音乐暂停
        musicPlayerManager.stop();
        progressBarHandler.setProgress(0);
        Toast.makeText(this,"初始化完毕",Toast.LENGTH_LONG).show();
        recreate();

    }

    @Override
    public void initListener() {
        btnStart.setOnClickListener(this::onClick);
        btnOrder.setOnClickListener(this::onClick);
        btnLast.setOnClickListener(this::onClick);
        btnNext.setOnClickListener(this::onClick);
    }

    /**
     * 播放按钮UI更新逻辑.
     */
    public void updateStartButtonStatus() {
        if (musicPlayerManager.isPlaying()) {
            btnStart.setImageResource(R.drawable.pause);
        } else {
            btnStart.setImageResource(R.drawable.play);
        }
    }

    private void onClick(View view) {
        switch (view.getId()) {
            // 上一曲
            case R.id.btnLast:
                mService.last();
                updateStartButtonStatus();
                break;
            // 播放/暂停
            case R.id.btnStar:
                mService.play(mService.getPosition(), false);
                updateStartButtonStatus();
                break;
            // 停止
            case R.id.btnOrder:
                mService.order();
                updateOrederText();
                break;
            // 下一曲
            case R.id.btnNext:
                mService.nextMusic();
                updateStartButtonStatus();
                break;
            default:
                break;
        }
    }

    private void updateOrederText() {
        int mode = mService.getCurrentPlayMode();
        switch (mode) {
            case MusicService.LIST:

                mService.order();
                btnOrder.setImageResource(R.drawable.random);
                break;
            case MusicService.RANDOM:
                mService.order();
                btnOrder.setImageResource(R.drawable.repeat);
                break;
            case MusicService.LOOP:
                mService.order();
                btnOrder.setImageResource(R.drawable.order);

                break;
            default:
                btnOrder.setImageResource(R.drawable.order);
                break;
        }

    }

    public void initData() {
        // 请求读写权限
        new RxPermissions(this).request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(result -> {
            if (!result) {
                showToast(getString(R.string.usb_perrmission));
            } else {
                showInitLoadView();
                if (mService != null) {
                    songsList = mService.getSonglist();
                    if (songsList != null && !songsList.isEmpty()) {
                        hideNoDataView();
                        //mAdapter.refresh(songsList);
                    } else {
                        showNoDataView();
                    }
                }
            }
        });
    }

    private void updatePlayButton(boolean isPlaying) {
        btnStart.setImageResource(isPlaying ? R.drawable.pause : R.drawable.play);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * Gets tool bar title.
     *
     * @return the tool bar title
     */
    public String getToolBarTitle() {
        return getResources().getString(R.string.usb_name);
    }

    @Override
    public int getToolBarRightImg() {
        return R.drawable.ic_baseline_autorenew_24;
    }


    @Override
    public int onBindLayout() {
        return R.layout.activity_main;
    }

    // 触发开始按钮点击事件的方法
    public void triggerStartButton() {
        btnStart.performClick();
    }
}
